from typing import Dict, Optional, List, Tuple
from database import db_manager

class ProxyConfig:
    """代理配置管理类 - 改为使用数据库存储"""
    
    def save_proxy_settings(self, proxy_ip: str, proxy_user: str = "", proxy_password: str = "", name: str = "") -> bool:
        """保存代理设置到数据库（新增或更新）"""
        name = name or proxy_ip
        return db_manager.save_proxy_settings(name, proxy_ip, proxy_user, proxy_password)
    
    def load_all_proxy_settings(self) -> List[Dict[str, str]]:
        """加载所有代理设置（来自数据库）"""
        return db_manager.get_all_proxy_settings()
    
    def load_proxy_settings(self, name: str = "") -> Dict[str, str]:
        """加载指定的代理设置（兼容旧接口，默认返回第一个）"""
        all_settings = self.load_all_proxy_settings()
        if not all_settings:
            return {"ProxyIp": "", "ProxyUser": "", "ProxyPassword": ""}
        if name:
            setting = db_manager.get_proxy_by_name(name)
            return setting or all_settings[0]
        return all_settings[0]
    
    def get_proxy_by_name(self, name: str) -> Optional[Dict[str, str]]:
        """根据名称获取代理配置（数据库）"""
        return db_manager.get_proxy_by_name(name)
    
    def delete_proxy_settings(self, name: str = "") -> bool:
        """删除代理设置（数据库）"""
        return db_manager.delete_proxy_settings(name or None)
    
    def get_proxy_url(self, name: str = "") -> Optional[str]:
        """获取代理URL"""
        settings = self.load_proxy_settings(name)
        proxy_ip = settings.get("ProxyIp", "").strip()
        proxy_user = settings.get("ProxyUser", "").strip()
        proxy_password = settings.get("ProxyPassword", "").strip()
        
        if not proxy_ip:
            return None
        
        if proxy_user and proxy_password:
            return f"http://{proxy_user}:{proxy_password}@{proxy_ip}"
        else:
            return f"http://{proxy_ip}"
    
    def get_all_proxy_names(self) -> List[str]:
        """获取所有代理配置的名称"""
        all_settings = self.load_all_proxy_settings()
        return [proxy.get("name", proxy.get("ProxyIp", "未命名")) for proxy in all_settings]
    
    def validate_proxy_settings(self, proxy_ip: str, proxy_user: str = "", proxy_password: str = "") -> Tuple[bool, str]:
        """验证代理设置"""
        if not proxy_ip.strip():
            return False, "代理IP地址不能为空"
        
        # 这里可以添加更多的验证逻辑
        # 例如：检查IP格式、端口号等
        
        return True, "验证通过"
    
    def update_current_proxy(self, name: str):
        """更新当前使用的代理配置（如需全局缓存可在此扩展）"""
        # 目前 http_client 直接通过 name 提取代理，不需要在此持久化
        return

# 全局代理配置实例
proxy_config = ProxyConfig() 